package br.edu.fatecou.reserva.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.edu.fatecou.reserva.dominio.Local;
import br.edu.fatecou.reserva.util.HibernateUtil;

public class LocalDAO {
	public void salvar(Local local) throws Exception {
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		Transaction transacao = sessao.beginTransaction();
		sessao.saveOrUpdate(local);
		transacao.commit();
		sessao.close();
	}

	public void editar(Local local) throws Exception {
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		Transaction transacao = sessao.beginTransaction();
		sessao.update(local);
		transacao.commit();
		sessao.close();
	}

	public void excluir(Local local) throws Exception {
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		Transaction transacao = sessao.beginTransaction();
		sessao.delete(local);
		transacao.commit();
		sessao.close();
	}

	public Local buscar(Long codigo) throws Exception {
		Session sessao = HibernateUtil.getSessionFactory().openSession();

		Criteria consulta = sessao.createCriteria(Local.class);
		consulta.add(Restrictions.idEq(codigo));

		Local resultado = (Local) consulta.uniqueResult();
		sessao.close();

		return resultado;
	}

	@SuppressWarnings("unchecked")
	public List<Local> buscar(String descricao) throws Exception {
		Session sessao = HibernateUtil.getSessionFactory().openSession();

		Criteria consulta = sessao.createCriteria(Local.class);
		consulta.add(Restrictions.like("descricao", "%" + descricao + "%"));
		consulta.addOrder(Order.asc("descricao"));

		List<Local> lista = consulta.list();
		sessao.close();

		return lista;
	}

	@SuppressWarnings("unchecked")
	public List<Local> buscar(String descricao, Byte quantidade)
			throws Exception {
		Session sessao = HibernateUtil.getSessionFactory().openSession();

		Criteria consulta = sessao.createCriteria(Local.class);

		Conjunction e = Restrictions.conjunction();
		e.add(Restrictions.eq("descricao", descricao));
		e.add(Restrictions.ne("quantidade", quantidade));

		consulta.add(e);

		List<Local> lista = consulta.list();
		sessao.close();

		return lista;
	}
}
